<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\AdminUser;
use App\Models\V1\WeChatLogin;
use App\Models\V1\NewStudent;
use App\Models\V1\ScrollImages;
use App\Models\V1\RecordsIdentity;
use App\Models\V1\RecordsPay;
use App\Models\V1\RecordsTextbook;
use App\Models\V1\RecordsDormitoryKey;
use App\Models\V1\RecordsDailyUse;
use App\Models\V1\ReceiveStatus;
use App\Models\V1\ApplyPays;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Log;
use App\Models\V1\NewArrival;

class SmallProgramController extends BaseController
{

    protected $app_id = 'wx6397396df988f501';
    protected $app_secret = 'f767a74b8fa834acbdf55971e858cb81';

    /**
     * 小程序端注册接口
     */
    public function register(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        //接收传递参数
        $reqParams = $request->all();

        //获取basic_new_student表中的数据
        $new_student_info = NewStudent::get();
        for ($i = 0; $i < count($new_student_info); $i++) {
            if ($reqParams['idNumber'] == $new_student_info[$i]->card_number) {
                $result['errorMsg'] = '您的身份证号已经存在';
                $result['errorCode'] = 401;
                return $result;
            }
        }
        //获取basic_new_student表中的数据
        $NewStudentInfo = NewStudent::get();
        for ($i = 0; $i < count($NewStudentInfo); $i++) {

            if ($reqParams['examCode'] == $NewStudentInfo[$i]->exam_code) {
                $result['errorMsg'] = '您的考试号已存在';
                $result['errorCode'] = 402;
                return $result;
            }
        }

        // 注册接口
        $successFlag = $this->handleRegister($reqParams);
        if ($successFlag) {
            $result['errorMsg'] = '注册成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '注册失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    private function handleRegister(array $params)
    {
        $name = isset($params['name']) ? $params['name'] : '';            //姓名
        $id_number = isset($params['idNumber']) ? $params['idNumber'] : '';    //身份证号(唯一)
        $exam_code = isset($params['examCode']) ? $params['examCode'] : '';    //准考证号(唯一)
        $password = isset($params['password']) ? $params['password'] : '';    //密码
        $js_code = isset($params['jsCode']) ? $params['jsCode'] : '';      //json code
        $encrypted_data = isset($params['encryptedData']) ? $params['encryptedData'] : '';
        $iv = isset($params['iv']) ? $params['iv'] : '';
        $third_session = isset($params['thirdSession']) ? $params['thirdSession'] : '';

        $apiStr = 'sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->app_secret . '&js_code=' . $js_code . '&grant_type=authorization_code';

        //获取小程序openid
        $resultData = $this->weixinGet($apiStr, []);
        $resultData = json_decode($resultData, true);

        //赋值openid
        $openid = $resultData['openid'];

        //获取当前arrival_code
        $arrival_code = $this->getArrivalCodes();

        $new_student_data = [
            'arrival_code' => $arrival_code,
            'enrollment_numbering' => '',
            'exam_code' => $exam_code,
            'name' => $name,
            'card_type' => '身份证',
            'card_number' => $id_number,
        ];
        $successFlag0 = NewStudent::updateOrCreate(['exam_code' => $exam_code], $new_student_data);

        $wechat_login_data = [
            'unionid' => $openid,
            'openid' => $openid,
            'exam_code' => $exam_code,
        ];
        $successFlag = WeChatLogin::updateOrCreate(['unionid' => $openid], $wechat_login_data);

        $admin_user_data = [
            'code' => $exam_code,
            'password' => bcrypt($password),
            'is_staff' => 0,
        ];
        $successFlag1 = AdminUser::updateOrCreate(['code' => $exam_code], $admin_user_data);

        if (($successFlag0 == true) && ($successFlag == true) && ($successFlag1 == true)) {
            return 1;
        } else {
            return 0;
        }
    }

    //get 微信接口
    public function weixinGet($apiStr, $header)
    {
        $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.weixin.qq.com/']);
        $res = $client->request('GET', $apiStr, ['headers' => $header]);
        $statusCode = $res->getStatusCode();
        $header = $res->getHeader('content-type');

        $data = $res->getBody();

        return $data;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn', true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    //① 小程序扫码, 身份确认
    public function studentIdentity(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $reqParams = $request->all();
        $userId = isset($reqParams['userId']) ? $reqParams['userId'] : '';
        $insert_data = [
            'student_code' => $userId,
        ];
        $info = RecordsIdentity::updateOrCreate(['id' => null], $insert_data);

        if ($info) {

            // 判断数据库中对应学生数据是否存在, 若存在获取id值
            $Status = ReceiveStatus::where('exam_code', $userId)
                ->where('type', 1)
                ->first();

//            if (!empty($Status) || isset($Status)) {
//                // 如果存在, 则更新status值
//                $successFlag = ReceiveStatus::where('exam_code', $userId)
//                    ->where('type', 1)
//                    ->update([
//                        'status' => 0,
//                        'updated_at' => Carbon::now()
//                    ]);
//            } else {
            if (!isset($Status)) {
                // 如果不存在, 则插入一条该数据
                $successFlag = ReceiveStatus::create([
                    'exam_code' => $userId,
                    'type' => 1,
                    'status' => 4,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ]);
            }

            $result['errorMsg'] = '扫码成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '扫码失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    //② 小程序扫码, 现场缴费
    public function studentPay(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $reqParams = $request->all();
        $userId = isset($reqParams['userId']) ? $reqParams['userId'] : '';
        $insert_data = [
            'student_code' => $userId,
        ];
        $info = RecordsPay::updateOrCreate($insert_data);

        if ($info) {

            // 判断数据库中对应学生数据是否存在
            $Status = ApplyPays::where('exam_code', $userId)
                ->first();

            $successFlag = 0;
            if (!empty($Status) || isset($Status)) {
                // 如果存在, 则更新status值
                $successFlag = ApplyPays::where('exam_code', $userId)
                    ->update([
                        'status' => 0,
                        'updated_at' => Carbon::now()
                    ]);
            }

            $result['errorMsg'] = '扫码成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '扫码失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    //③ 小程序扫码, 生活用品发放
    public function studentDailyUse(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $reqParams = $request->all();
        $userId = isset($reqParams['userId']) ? $reqParams['userId'] : '';
        $insert_data = [
            'student_code' => $userId,
        ];
        $info = RecordsDailyUse::updateOrCreate($insert_data);

        if ($info) {

            // 判断数据库中对应学生数据是否存在, 若存在获取id值
            $Status = ReceiveStatus::where('exam_code', $userId)
                ->where('type', 2)
                ->first();

//            if(!empty($Status)||isset($Status)){
//                // 如果存在, 则更新status值
//                $successFlag = ReceiveStatus::where('exam_code', $userId)
//                        ->where('type', 2)
//                        ->update([
//                            'status' => 0,
//                            'updated_at'=>Carbon::now()
//                        ]);
//            }else{
            // 如果不存在, 则插入一条该数据
            if (!isset($Status)) {
            $successFlag = ReceiveStatus::create([
                'exam_code' => $userId,
                'type' => 2,
                'status' => 4,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);
            }

            $result['errorMsg'] = '扫码成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '扫码失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    //④ 小程序扫码, 教材发放
    public function studentTextbook(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $reqParams = $request->all();
        $userId = isset($reqParams['userId']) ? $reqParams['userId'] : '';

        $insert_data = [
            'student_code' => $userId,
        ];
        $info = RecordsTextbook::updateOrCreate($insert_data);

        if ($info) {

            // 判断数据库中对应学生数据是否存在, 若存在获取id值
            $Status = ReceiveStatus::where('exam_code', $userId)
                ->where('type', 3)
                ->first();

//            if(!empty($Status)||isset($Status)){
//                // 如果存在, 则更新status值
//                $successFlag = ReceiveStatus::where('exam_code', $userId)
//                        ->where('type', 3)
//                        ->update([
//                            'status' => 0,
//                            'updated_at'=>Carbon::now()
//                        ]);
//            }else{
            // 如果不存在, 则插入一条该数据
            if (!isset($Status)) {
            $successFlag = ReceiveStatus::create([
                'exam_code' => $userId,
                'type' => 3,
                'status' => 4,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]);
            }

            $result['errorMsg'] = '扫码成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '扫码失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    //⑤ 小程序扫码, 宿舍钥匙发放
    public function studentDormitoryKey(Request $request)
    {
        //自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $reqParams = $request->all();
        $userId = isset($reqParams['userId']) ? $reqParams['userId'] : '';
        $insert_data = [
            'student_code' => $userId,
        ];
        $info = RecordsDormitoryKey::updateOrCreate(['id' => null], $insert_data);

        if ($info) {

            // 判断数据库中对应学生数据是否存在, 若存在获取id值
            $Status = ReceiveStatus::where('exam_code', $userId)
                ->where('type', 5)
                ->first();

//            if(!empty($Status)||isset($Status)){
//                // 如果存在, 则更新status值
//                $successFlag = ReceiveStatus::where('exam_code', $userId)
//                        ->where('type', 5)
//                        ->update([
//                            'status' => 0,
//                            'updated_at'=>Carbon::now()
//                        ]);
//            }else{
            // 如果不存在, 则插入一条该数据
            if (!isset($Status)) {
                $successFlag = ReceiveStatus::insert([
                    'exam_code' => $userId,
                    'type' => 5,
                    'status' => 4,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ]);
            }

//            }

            $result['errorMsg'] = '扫码成功';
            $result['errorCode'] = Response::HTTP_OK;
        } else {
            $result['errorMsg'] = '扫码失败';
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

}
